<?php
//Plugin: inactive score reduction script
//Author: Grief-Code (ICanHasGrief)
//This plugin automatically reduce score points after a specific time if the user is inactive

if (!isset($website) ) { header('HTTP/1.1 404 Not Found'); die; }


$PluginEnabled = '1';
//Enable edit plugin options
$PluginOptions = '1';

$ScoreReduction = '5';
$InactiveTime = '30';
$MarkOnly = '1';
$ExcludePlayers = '1';
$MarkTop = '1';

define('OS_ScoreAmount', $ScoreReduction );
define('OS_InactiveTime', $InactiveTime );

define('OS_Exlude', $ExcludePlayers );
define('OS_MarkOnly', $MarkOnly );

define('OS_MarkTop', $MarkTop );
if ($PluginEnabled == 1) {

  if ( OS_is_admin() AND OS_PluginEdit() ) {
  
  	$ScoreReduction = OS_ScoreAmount;
	$InactiveTime = OS_InactiveTime;
	$ExcludePlayers = OS_Exlude;
	$MarkTop = OS_MarkTop;
	$MarkOnly = OS_MarkOnly;

     if ( isset($_POST["OS_ScoreReduction"]) ) {
	 
     $ScoreReduction = safeEscape($_POST["OS_ScoreReduction"]);
	 $InactiveTime = safeEscape($_POST["OS_InactiveTime"]);
	 
	 $ExcludePlayers = safeEscape(  $_POST["OS_ExcludePlayers"]);
	 $MarkTop= safeEscape(  $_POST["OS_MarkTop"]);
	 $MarkOnly= safeEscape(  $_POST["OS_MarkOnly"]);

	 if ( $ScoreReduction>=50 OR $ScoreReduction<=0 ) $ScoreReduction = 5;
	 if ( $InactiveTime<=7 ) $InactiveTime = 14;
	 
     write_value_of('$ScoreReduction', "$ScoreReduction", $ScoreReduction , $plugins_dir.basename(__FILE__, '') );
	 write_value_of('$InactiveTime', "$InactiveTime", $InactiveTime , $plugins_dir.basename(__FILE__, '') );
	 write_value_of('$ExcludePlayers', "$ExcludePlayers", $ExcludePlayers , $plugins_dir.basename(__FILE__, '') );
	write_value_of('$MarkTop', "$MarkTop", $MarkTop , $plugins_dir.basename(__FILE__, '') );
	write_value_of('$MarkOnly', "$MarkOnly", $MarkOnly , $plugins_dir.basename(__FILE__, '') );

    }
	
    $sel = array();
    $sel1 = array();
    $sel2 = array();
    
	if ($ExcludePlayers == 1) $sel[0] = 'selected = "selected"'; else $sel[0]='';
	if ($ExcludePlayers == 0) $sel[1] = 'selected = "selected"'; else $sel[1]='';
      	if ($MarkTop == 1) $sel1[0] = 'selected = "selected"'; else $sel1[0]='';
	if ($MarkTop == 0) $sel1[1] = 'selected = "selected"'; else $sel1[1]='';
	if ($MarkOnly == 1) $sel1[0] = 'selected = "selected"'; else $sel1[0]='';
        if ($MarkOnly == 0) $sel1[1] = 'selected = "selected"'; else $sel1[1]='';

	
	$Option = '
<form action="" method="post" >
  <div>Score Reduction: <input size="2" type="text" value="'.$ScoreReduction.'" name="OS_ScoreReduction" /> score</div>
  <div>Time a user is set as inactive: <input size="2" type="text" value="'.$InactiveTime.'" name="OS_InactiveTime" /> days.</div>
  
  <div>Exclude admins and safelisted players: 
  <select name="OS_ExcludePlayers">
    <option '.$sel[0].' value="1">Yes</option>
	<option '.$sel[1].' value="0">No</option>
  </select>
  </div>
  <div>Mark inactive users on top page:
  <select name="OS_MarkTop">
    <option '.$sel1[0].' value="1">Yes</option>
        <option '.$sel1[1].' value="0">No</option>
  </select>
  </div>
  <div>Mark only, dont reduce points:
  <select name="OS_MarkOnly">
    <option '.$sel1[0].' value="1">Yes</option>
        <option '.$sel1[1].' value="0">No</option>
  </select>
  </div>
  
  <input type="submit" value = "Save" class="menuButtons" />
  <a href="'.OS_HOME.'adm/?plugins" class="menuButtons">Cancel</a>
</form>';

  }

function RecreateTable( ) {
	global $db;
	$sth = $db->prepare("DROP TABLE IF EXISTS `inactive`" );
	$result = $sth->execute();
        $sth2 = $db->prepare("CREATE TABLE IF NOT EXISTS `inactive` (
		`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                `name` VARCHAR( 30 ) NOT NULL,
		`days` INT NOT NULL
                ) ENGINE = MYISAM ;" );
	 $result2 = $sth2->execute();
}

function SelectAllUsers( ) {
	global $db;
	global $InactiveTime;
	$inactivelist = array( );
	$sth = $db->prepare("SELECT name FROM ".OSDB_GP." GROUP BY name;" );
        $result = $sth->execute();
	$creation = false;
        while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
		$sth2 = $db->prepare("SELECT gameid FROM ".OSDB_GP." WHERE name='".$row["name"]."' ORDER BY id DESC LIMIT 1;" );
		$result2 = $sth2->execute();
		while ($row2 = $sth2->fetch(PDO::FETCH_ASSOC)) {
			$sth3 = $db->prepare("SELECT TIMESTAMPDIFF(day, datetime, NOW( ) ) AS lastgame FROM ".OSDB_GAMES." WHERE id = '".$row2["gameid"]."';" );
			$result3 = $sth3->execute();
			while ($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
				if( $row3["lastgame"] >= $InactiveTime )
				{
					$sth4 = $db->prepare("INSERT INTO inactive ( name, days ) VALUES ( '".strtolower($row["name"])."', '".($row3["lastgame"]-$InactiveTime)."' );");
					$result4 = $sth4->execute();
				}
			}
		}
	}
}

function MarkTopPage( ) {
	global $TopData;
	global $UserData;
	global $db;
	global $ExcludePlayers;
        //Top page
        if ( !empty($TopData) ) {

          for ($c=0; $c<count($TopData); $c++ )
	  {
		$sth = $db->prepare("show tables LIKE 'inactive';");
		$result = $sth->execute( );
		if( $sth->rowCount() != 0 )
		{
                        $EP = false;
                        if( $ExcludePlayers )
                        {
                                $sth2 = $db->prepare( "SELECT admin, safelist FROM ".OSDB_STATS." WHERE player_lower = '".strtolower($TopData[$c]["player"])."';" );
                                $result2 = $sth2->execute( );
                                while ($row2 = $sth2->fetch(PDO::FETCH_ASSOC)) {
                                        if( $row2["safelist"] OR $row2["admin"] )
                                                $EP = true;
                                }
                                //recheck admins, might be not updated if they are inactive
                                global $RootAdmins;
                                $listofroots = explode( ",", $RootAdmins );
                                foreach( $listofroots as $root ) {
                                        if( strtolower($root) == strtolower($TopData[$c]["player"]) ) $EP = true;
                                }
                        }
			if( !$EP )
			{
				$sth3 = $db->prepare("SELECT name FROM inactive WHERE name = '".strtolower($TopData[$c]["player"])."';" );
				$result3 = $sth3->execute( );
				if( $sth3->rowCount() == 1 )
					$TopData[$c]["player"] = '<b><font color="red">'.$TopData[$c]["player"].'</font></b>';
			}
		}
	  }
	 return array($TopData);
	}
	if ( !empty($UserData) ) {
	  for ($c=0; $c<count($UserData); $c++ ) {
                $sth = $db->prepare("show tables LIKE 'inactive';");
                $result = $sth->execute( );
                if( $sth->rowCount() != 0 )
                {
                        $EP = false;
                        if( $ExcludePlayers )
                        {
                                $sth2 = $db->prepare( "SELECT admin, safelist FROM ".OSDB_STATS." WHERE player_lower = '".strtolower($UserData[$c]["player"])."';" );
                                $result2 = $sth2->execute( );
                                while ($row2 = $sth2->fetch(PDO::FETCH_ASSOC)) {
                                        if( $row2["safelist"] OR $row2["admin"] )
                                                $EP = true;
                                }
                                //recheck admins, might be not updated if they are inactive
                                global $RootAdmins;
                                $listofroots = explode( ",", $RootAdmins );
                                foreach( $listofroots as $root ) {
                                        if( strtolower($root) == strtolower($UserData[$c]["player"]) ) $EP = true;
                                }
                        }
                        if( !$EP )
                        {
                                $sth3 = $db->prepare("SELECT name FROM inactive WHERE name = '".strtolower($UserData[$c]["player"])."';" );
                                $result3 = $sth3->execute( );
                                if( $sth3->rowCount() == 1 )
                                        $UserData[$c]["player"] = '<b><font color="red">'.$UserData[$c]["player"].'</font></b>';
                        }
                }
	  }
	 return array($UserData);
        }
}

function ReduceInactive( ) {
	global $db;
	global $ScoreReduction;
	global $ExcludePlayers;
	$sth = $db->prepare( "SELECT name FROM inactive;" );
	$result = $sth->execute( );
	if( $sth->rowCount() != 0 )
	{
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
			$EP = false;
			if( $ExcludePlayers )
			{
				$sth2 = $db->prepare( "SELECT admin, safe FROM ".OSDB_STATS." WHERE player_lower = '".strtolower($row["name"])."';" );
				$result2 = $sth2->execute( );
				while ($row2 = $sth2->fetch(PDO::FETCH_ASSOC)) {
					if( $row2["safe"] OR $row2["admin"] )
						$EP = true;
				}
				//recheck admins, might be not updated if they are inactive
				global $RootAdmins;
	        	        $listofroots = explode( ",", $RootAdmins );
        	        	foreach( $listofroots as $root ) {
                        		if( strtolower($root) == strtolower($row["name"]) ) $EP = true;
				}
			}

			if( !$EP )
			{
				$sth3 = $db->prepare( "UPDATE ".OSDB_STATS." SET score = score-".$ScoreReduction." WHERE player_lower = '".strtolower($row["name"])."';" );
				$result3 = $sth3->execute( );
			}
		}
	}
}

//Basic programm

	$CurrentTime = time();
	$LastInactiveUpdateTime = OS_get_custom_field( 0, "last_inactive_update_stats" );

	if( $LastInactiveUpdateTime+86400 <= $CurrentTime ) $UpdateUsers = 1; else $UpdateUsers = 0;

	if( $UpdateUsers )
	{
		RecreateTable( );
		SelectAllUsers( );

		global $MarkOnly;
		if( !$MarkOnly )
			ReduceInactive( );

		OS_add_custom_field(0, "last_inactive_update_stats" ,  time() );
	}

	if( $MarkTop )
		MarkTopPage( );

}
?>
